import { ref, onMounted } from "vue";
import type { Ref } from "vue";
import type { IProduct } from "@/type/types";
import {useRouter} from 'vue-router'
import {
  RequestCategoryList,
  RequestShopListByCategoryId,
} from "@/api/product";

interface ICategory {
  id: number;
  text: string;
}

export const useCategory = () => {
  const activeId = ref(1);
  const activeIndex = ref(0);
  const categoryList: Ref<Array<ICategory>> = ref([]);
  const selectList: Ref<Array<IProduct>> = ref([]);

  // 商品分类
  const getCategoryList = async () => {
    let data = await RequestCategoryList();
    let { resultCode, resultInfo } = data;
    if (resultCode == 1) {
      let list = resultInfo.list;
      categoryList.value = list.map((item) => {
        return { id: item.id, text: item.name };
      });
      getShopListByCategoryId(categoryList.value[0].id);
    }
  };

  // 商品列表
  const getShopListByCategoryId = async (categoryId: number) => {
    let data = await RequestShopListByCategoryId(categoryId);
    let { resultCode, resultInfo } = data;
    if (resultCode == 1) {
      selectList.value = resultInfo.list;
    }
  };


  // 选中分类
  const onSelector = (index: number) => {
    let categoryId = categoryList.value[index].id;
    getShopListByCategoryId(categoryId);
  };
  onMounted(() => {
    getCategoryList();
  });

  return {
    activeId,
    activeIndex,
    categoryList,
    onSelector,
    selectList,
  };
};

// 商品详情
export const useProductDetail=()=>{
  const router = useRouter()
  const onDetail=(id:number)=>{
    router.push({path:'/detail/'+id})
  }
  return {onDetail}
}
